package com.project.wxServer.server.login.impl;

import com.alibaba.fastjson.JSONObject;
import com.project.common.constant.Constants;
import com.project.common.core.domain.AjaxResult;
import com.project.common.core.domain.entity.SysRole;
import com.project.common.core.domain.entity.SysUser;
import com.project.common.core.domain.entity.SysUserWx;
import com.project.common.exception.user.UserPasswordNotMatchException;
import com.project.common.utils.MessageUtils;
import com.project.common.utils.SecurityUtils;
import com.project.common.utils.StringUtils;
import com.project.framework.manager.AsyncManager;
import com.project.framework.manager.factory.AsyncFactory;
import com.project.framework.web.service.SysLoginService;
import com.project.system.service.ISysRoleService;
import com.project.system.service.ISysUserWxService;
import com.project.wxServer.domain.login.FullUserInfo;
import com.project.wxServer.domain.login.WXLoginBody;
import com.project.wxServer.server.login.ILoginService;
import com.project.wxServer.utils.CharUtil;
import com.project.wxServer.utils.CommonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * description：微信登录实现
 *
 * @author kang
 * @since 2021/6/29　14:09
 */
@Service
public class LoginServiceImpl implements ILoginService {

    private static final Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);

    //默认初始密码
    private static final String password = "123456";

    @Resource
    private SysLoginService loginService;

    @Resource
    private ISysUserWxService userWxService;
    
    @Resource
    private ISysRoleService roleService;


    /**
     * 微信登录方法
     *
     * @param fullUserInfo 微信登录信息
     * @return 结果
     */
    public AjaxResult wxLogin(FullUserInfo fullUserInfo) {
        if (null == fullUserInfo) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(
                    "", Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }

        //获取openId
        String jsonString = CommonUtil.getOpenId(fullUserInfo.getCode());
        Map jsonMap = JSONObject.parseObject(jsonString, Map.class);
        String openId = (String) jsonMap.get("openid");

        SysUserWx userWx = userWxService.selectSysUserWxByOpenId(openId);
        //判断是否访客登录
        if (StringUtils.isNotEmpty(openId)) {
            //已登录过的用户
            if (userWx == null) {
                WXLoginBody wxLoginBody = fullUserInfo.getUserInfo();
                SysUserWx newUser = new SysUserWx();
                String wxUsername = CharUtil.getRandomString(12);
                newUser.setUserName(wxUsername);
                newUser.setOpenId(openId);
                newUser.setNickName(wxLoginBody.getNickName());
                newUser.setAvatar(wxLoginBody.getAvatarUrl());
                newUser.setSex(wxLoginBody.getGender());
                newUser.setPassword(SecurityUtils.encryptPassword(password));
                newUser.setStatus("0");
                userWxService.insertSysUserWx(newUser);
            }
        }
        // 生成令牌
        AjaxResult ajax = AjaxResult.success();
        String refreshToken = loginService.login(openId, password, "", "");
        ajax.put(Constants.TOKEN, refreshToken);

        //返回一些必要信息
        Map<String, Object> map = new HashMap<>();
        map.put("sysUser", userWx.getSysUser());
        map.put("roles",userWx.getRoles());
        map.put("sysDept", userWx.getSysDept());
        map.put("openid", openId);
        ajax.put("userInfo", map);
        return ajax;
    }
}
